<template>
  <div class="preview">
    <div class="previewTop">
      <div class="previewTopTitle">页面预览</div>
      <el-button type="primary" @click="back">返回</el-button>
    </div>
    <div id="amisPreviewBox"></div>
  </div>

</template>

<script lang="ts" setup>
import {onMounted, ref, watch} from "vue";
import {menuDetail} from "@/api/menuManage";
import {useRoute, useRouter} from "vue-router";
import request from "@/utils/request";

const route = useRoute()
const router = useRouter()
const anisJson = ref<any>({})
const appId = ref('')


/**
 * 初始化 AMIS DOM 组件
 *
 * 使用 amisRequire 方法引入 AMIS 库，并通过 amis.embed 方法将 AMIS JSON 配置嵌入到指定的 DOM 元素中。
 */
function amisInitDom() {

  // @ts-ignore
  var amis = amisRequire('amis/embed');
  amis.embed('#amisPreviewBox', anisJson.value, {}, {
    fetcher: (req: any) => {
      let {
        url,
        method,
        data,
        query,
        config,
        headers,
      } = req;
      console.log(req)
      let tUrl = url && url.split('?')[0]
      if (method == 'get') {
        return request({
          url: tUrl,
          method: method,
          params: query,
          headers: {
            Appid: appId.value,
            ...headers
          }
        })
      } else {
        return request({
          url: tUrl,
          method: method,
          data: data,
          headers: {
            Appid: appId.value,
            ...headers
          }
        })
      }
    },
  });
}


function back() {
  router.go(-1)
}


watch(() => route, (val: any) => {

  appId.value = route.query.appId as string
  menuDetail((route as any).query.menuId).then((res: any) => {
    anisJson.value = res.data.data
    amisInitDom()

  })
}, {
  deep: true,
  immediate: true,
})
</script>
<style lang="scss" scoped>
#amisPreviewBox {
  box-sizing: border-box;
  position: relative;
  height: calc(100% - 43px);
  transform: translate(0);
}

.preview {
  width: 100%;
  height: 100vh;
  overflow: auto;
}

.previewTop {
  width: 100%;
  padding: 7px 10px;
  display: flex;
  justify-content: flex-end;
  background: #ebeef5;
  position: relative;
  z-index: 100;
  height:43px;

  &Title {
    text-align: center;
    flex: 1;
    font-size: 17px;
  }
}
</style>